/**
 * (created at 2011-1-19)
 */
package qiushuo.mysqlparser.ast.expression.comparison;

import qiushuo.mysqlparser.ast.expression.Expression;
import qiushuo.mysqlparser.generator.SQLType;

/**
 * @author <a href="mailto:QiuShuo1985@gmail.com">QIU Shuo</a>
 */
public class ComparasionIsExpression implements Expression {
    public static final int IS_NULL = 1;
    public static final int IS_TRUE = 2;
    public static final int IS_FALSE = 3;
    public static final int IS_UNKNOWN = 4;
    public static final int IS_NOT_NULL = 5;
    public static final int IS_NOT_TRUE = 6;
    public static final int IS_NOT_FALSE = 7;
    public static final int IS_NOT_UNKNOWN = 8;

    private final int mode;
    private final Expression operand;

    /**
     * @param mode {@link #IS_NULL} or {@link #IS_TRUE} or {@link #IS_FALSE} or
     *            {@link #IS_UNKNOWN} or {@link #IS_NOT_NULL} or
     *            {@link #IS_NOT_TRUE} or {@link #IS_NOT_FALSE} or
     *            {@link #IS_NOT_UNKNOWN}
     */
    public ComparasionIsExpression(Expression operand, int mode) {
        this.operand = operand;
        this.mode = mode;
    }

    @Override
    public String generateSql(SQLType type) {
        switch (type) {
        case MySQL:
            StringBuilder sb = new StringBuilder();
            if (operand.getPrecedence() < getPrecedence()) {
                sb.append('(').append(operand.generateSql(type)).append(')');
            } else {
                sb.append(operand.generateSql(type));
            }
            sb.append(' ');
            switch (mode) {
            case IS_NULL:
                sb.append("IS NULL");
                break;
            case IS_TRUE:
                sb.append("IS TRUE");
                break;
            case IS_FALSE:
                sb.append("IS FALSE");
                break;
            case IS_UNKNOWN:
                sb.append("IS UNKNOWN");
                break;
            case IS_NOT_NULL:
                sb.append("IS NOT NULL");
                break;
            case IS_NOT_TRUE:
                sb.append("IS NOT TRUE");
                break;
            case IS_NOT_FALSE:
                sb.append("IS NOT FALSE");
                break;
            case IS_NOT_UNKNOWN:
                sb.append("IS NOT UNKNOWN");
                break;
            default:
                throw new IllegalArgumentException("unknown mode for IS expressin: " + mode);
            }
            return sb.toString();
        default:
            throw new UnsupportedOperationException("only mysql sql can be generated");
        }
    }

    @Override
    public int getPrecedence() {
        return PRECEDENCE_COMPARISION;
    }

}
